import java.nio.FloatBuffer;
import java.util.PriorityQueue;

/**
 * @Author: XXHH
 * @CreateTime: 2025-05-02
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    private long time;
    private Runnable task;

    public MyTimerTask(Runnable task,long time) {
        this.time = time;
        this.task = task;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.getTime()-o.getTime());
    }

    public void run(){
        task.run();
    }
    public long getTime(){
        return this.time;
    }
}
class MyTimer{
    // 优先级队列
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();
    public MyTimer(){
        Thread t = new Thread(()->{
            try {
                while (true){
                    if (queue.isEmpty()){
                        locker.wait();
                    }
                    MyTimerTask task = queue.peek();
                    if (System.currentTimeMillis() < task.getTime()){
                        // 如果当前时间比 任务的时间少，那么说明还没有到达指定的时间
                        locker.wait(task.getTime()-System.currentTimeMillis());
                        continue;
                    }else {
                        task.run();
                        queue.poll();
                    }
                }
            }catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t.start();
    }
    public void schedule(Runnable task,long delay){
        synchronized (locker){
            MyTimerTask myTimerTask = new MyTimerTask(task, delay + System.currentTimeMillis());
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}
public class Demo41 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
    }
}
